//
//  WYNetworkTool+News.m
//  WYNews
//
//  Created by 曾佳豪 on 2017/3/20.
//  Copyright © 2017年 haodada.com. All rights reserved.
//

//所有关于新闻的数据都在放在这个分类
#import "WYNetworkTool+News.h"
#import <YYModel.h>
#import "WYNewsModel.h"
@implementation WYNetworkTool (News)

-(void)requestNewList:(NSString *)tid callBack:(void (^)(NSArray *))callBack{
    //创建url
    NSString *url =[NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/%@/0-20.html", tid];
    [[WYNetworkTool sharedTool]reqeustWith:url method:@"GET" parameters:nil callBack:^(id response) {
        
        //判断服务器是否返回nil 如果为nil就直接回调 告诉失败
        //不等于nil 就字典转模型 返回模型数组
        
        if (response !=nil) {
            //获取字典数组
            NSArray *dicArr =response[tid];
            //字典转模型
            NSArray *modelArry =[NSArray yy_modelArrayWithClass:[WYNewsModel class] json:dicArr];
            //返回模型数组
            callBack(modelArry);
        }else{
            callBack (nil);
        }
    }];
    
}
//获取网易新闻的详细页的数据
//参数1 新闻id
//参数2.完成回调 网易新闻正文的html字符串返回
-(void)requestNewsDetail:(NSString *)docId callBack:(void(^)(NSString *bodyString))callBack{
    
    //拼接新闻详细页的接口
    NSString *urlString =[NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",docId];
    
    [[WYNetworkTool sharedTool]reqeustWith:urlString method:@"GET" parameters:nil callBack:^(id response) {
       //获取详细页的数据的字典(最外层的)
        NSDictionary *bodyDic =response[docId];
        //详细页的正文的html的字符串
        NSString *bodyStr =bodyDic[@"body"];
        
        
        //--------
        
        //正文中所有的图片信息的字典数组
        NSArray *imageArr =bodyDic[@"img"];
        
        //加载正文字符串
        //拿到css字符串
        NSString *css =[NSString stringWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"news.css" withExtension:nil ] encoding:NSUTF8StringEncoding error:NULL];
        
        //将所有的注释掉的 `<!--IMG#0-->` 格式的图片字符串,替换成html中img标签
        for (NSDictionary *img in imageArr) {
            //拼接
            NSString *imgHtml =[NSString
                                stringWithFormat:
                                @"<img src=%@>",img[@"src"]];
            //替换掉ref的字符串  =img标签
            bodyStr =[bodyStr stringByReplacingOccurrencesOfString:img[@"ref"] withString:imgHtml];
        }
    //将css 与body的正文拼接成一个完整的html字符串
        NSString *html =[NSString stringWithFormat:@"%@%@",css,bodyStr];
        callBack(html);
    }];
    
}
@end
